// https://api.nevegy.com/manage/single/acarea.html?edit=update&type=1&locid=1000&devid=3
// https://api.nevegy.com/manage/single/acarea.html?edit=update&type=1&locid=1129&devid=12&mac=ECDA3BBDEE8C&u=nvgadmin@nevegy.com&p=Nvg3PA$$w0rd
let urlmac = urlParma.mac;
let areaMode: any = {};
if (urlmac) {
  document.title = 'manage device';
} else {
  document.title = 'manage';
}

console.log(urlParma);
let locs: any = localStorage.getItem('locs');

if (!urlParma.u || !urlParma.p) {
  backlogin();
} else if (urlParma.u && urlParma.p) {
  axios({
    method: 'post',
    url: 'https://api.nevegy.com/index.php/api/manage?mtd=Login',
    data: {
      user: urlParma.u,
      password: urlParma.p
    }
  })
    .then(function (response: any) {
      if (Number(response.data.code) === 200) {
        setLan();
        getType1(urlParma);
      } else {
        backlogin();
      }
    });
}
// else if (locs) {
//   locs = JSON.parse(locs);
//   console.log(locs.includes(Number(urlParma.locid)));
//   if (!locs.includes(Number(urlParma.locid))) {
//     // backlogin();
//     alert('Wrong location id');
//   } else {
//     setLan();
//     getType1(urlParma);
//   }
// }


function backlogin() {
  let urlp = Object.assign({}, urlParma);
  if (urlp.u) delete urlp.u;
  if (urlp.p) delete urlp.p;
  let path: string = location.pathname.replace(/[a-z]+.html/g, '');
  let html = location.pathname.replace(path, '');
  // console.log(path, html);
  urlp.path = path;
  urlp.html = html;
  localStorage.setItem('urlParma', JSON.stringify(urlp));
  location.href = 'login.html';
}

function getType1(params: any) {
  const {devid, locid, type} = params;
  axios({
    method: 'post',
    url: 'https://api.nevegy.com/index.php/api/manage?mtd=GetInfoByToken',
    data: {
      devId: devid,
      type: type,
      locationId: locid,
    }
  })
    .then(function (response: any) {
      type1(response.data.data);
      if (urlmac) {
        axios({
          method: 'post',
          url: 'https://api.nevegy.com/index.php/api/manage?mtd=GetACDevInfo',
          data: {
            areaId: devid,
            mac: urlmac,
            locationId: locid,
          }
        })
          .then(function (response: any) {
            acdev(response.data.data);
            hideLoading();
          });
      } else {
        hideLoading();
      }
    });
}

function hideLoading() {
  $('#loading').addClass('none');
}

function tempMath(id: any, type: any) {
  let temp = Number($(id).html());
  if (type === 'plus')
    temp = temp + 0.5;
  if (type === 'minus')
    temp = temp - 0.5;
  temp = temp >= 40 ? 40 : temp;
  temp = temp <= 12 ? 12 : temp;
  $(id).html(temp);
}

function tempEvent(btnID: any, tempID: any, type: any) {
  let temptime1: any, temptime2: any;
  $(btnID).on('click', () => {
    tempMath(tempID, type);
  }).on('mousedown', () => {
    temptime1 = setTimeout(() => {
      temptime2 = setInterval(() => {
        tempMath(tempID, type);
      }, 100);
    }, 1000);
  }).on('mouseup', () => {
    clearInterval(temptime2);
    clearInterval(temptime1);
  });
}

function manmodeToggle(disabled: any) {
  if (!urlmac) {
    document.querySelector('#backauto')?.classList.toggle('none', disabled);
    document.querySelector('[for="backauto"]')?.classList.toggle('none', disabled);
    document.querySelector('[for="allowIndep"] + div')?.classList.toggle('none', !disabled);
    document.querySelector('[for="allowIndep"]')?.classList.toggle('none', !disabled);
  } else {
    document.querySelector('[for="allowIndep"] + div')?.classList.toggle('none', true);
    document.querySelector('[for="allowIndep"]')?.classList.toggle('none', true);
  }
  
  
  

  $('[name="deviceDays"]').attr('disabled', disabled);
  $('.time select, .time input').attr('disabled', disabled);

  if (urlmac) {
    $('[name="allowIndep"]').attr('disabled', disabled);
    $('[name="fanMode_manual"]').attr('disabled', disabled);
    $('[name="acMode_manual"]').attr('disabled', disabled);
    $('#plusTempManual').attr('disabled', disabled);
    $('#minusTempManual').attr('disabled', disabled);
  }
}

function manModeVals(obj: any) {
  const {fanmode, acmode, targettemp} = obj;
  // console.log(obj);
  $('[name="fanMode_manual"]').attr('checked', false);
  $('[name="fanMode_manual"][value="' + fanmode + '"]').attr('checked', true);
  $('[name="acMode_manual"]').attr('checked', false);
  $('[name="acMode_manual"][value="' + acmode + '"]').attr('checked', true);
  $('#temperature_manual').html(targettemp / 10);
}

function type1(data: any) {
  console.log(data);
  const {area_info, location_info} = data;

  let aids = area_info.map((item: any) => item.id);
  if (!aids.includes(Number(urlParma.devid))) {
    // backlogin();
    alert('wrong devid(area id)');
  }


  tempEvent('#plusTemp', '#temperature', 'plus');
  tempEvent('#minusTemp', '#temperature', 'minus');
  tempEvent('#plusTempManual', '#temperature_manual', 'plus');
  tempEvent('#minusTempManual', '#temperature_manual', 'minus');
  $('#areaLocation option').eq(0).val(location_info.id).text(location_info.nameEn);
  if (area_info.length) {
    const index = area_info.findIndex((item: any) => Number(urlParma.devid) === item.id);
    const {
      aname,
      allowindependent,
      fanmode,
      acmode,
      targettemp,
      manmode,
      manfanmode,
      manacmode,
      mantargettemp,
      weekdays,
      t1mode,
      t2mode,
      t3mode,
      t1on,
      t1off,
      t2on,
      t2off,
      t3on,
      t3off,
      mantimetoauto
    } = area_info[index];
    areaMode = {fanmode, acmode, targettemp, manfanmode, manacmode, mantargettemp};
    $('#areaName').val(aname);
    $('[name="allowIndep"][value="' + allowindependent + '"]').attr('checked', true);
    $('[name="manualMode"][value="' + manmode + '"]').attr('checked', true);
    if (mantimetoauto !== 0) {
      $('#backauto').val(transToTime(String(mantimetoauto)));
    }
    if (manmode === 0) {
      mode0(areaMode);
    }
    if (manmode === 1) {
      mode1(areaMode);
    }
    if (!urlmac) {
      $('[name="manualMode"]').on('click', (event: any) => {
        console.log(2)
        if ($('[name="manualMode"]:checked').val() === '1') {
          mode1(areaMode);
        } else {
          mode0(areaMode);
        }
      });
    }

    const weekdom: any = Array.from(document.querySelectorAll('[name="deviceDays"]'));
    weekdays.split('').map((item: any, index: any) => {
      weekdom[index].checked = Number(item) === 1;
    });
    $('#switchModeP1T1').val(t1mode);
    $('#switchModeP1T2').val(t2mode);
    $('#switchModeP1T3').val(t3mode);
    $('.time select').each(function (i: any, item: any) {
      checktimer(item);
    });
    $('#port1Timer1Start').val(transToTime(String(t1on)));
    $('#port1Timer1End').val(transToTime(String(t1off)));
    $('#port1Timer2Start').val(transToTime(String(t2on)));
    $('#port1Timer2End').val(transToTime(String(t2off)));
    $('#port1Timer3Start').val(transToTime(String(t3on)));
    $('#port1Timer3End').val(transToTime(String(t3off)));
  }
  $('.time select').on('change', (event: any) => {
    checktimer(event.target);
  });
  $('#btn_create').on('click', () => {
    const {devid, type} = urlParma;
    const weekdays: any = Array.from(document.querySelectorAll('[name="deviceDays"]')).map((item: any) => {
      return item.checked ? 1 : 0;
    });
    let backAuto = $('#backauto').val().split(':').join('');
    const manualMode = $('[name="manualMode"]:checked').val();
    console.log(backAuto);
    let url: string = 'https://api.nevegy.com/index.php/api/manage?mtd=ModifyDevices';
    let submitParams: any = {
      // token: "32c943c213e42d179cbeb7871ba3e410", // token
      // type: "1", // type
      // locationId: "1102", // location_info.id
      // devId: "2", // devid
      // token,
      act: 'upd',
      type,
      locationId: location_info.id,
      devId: devid,
      deviceName: $('#areaName').val(),
      manualMode,
      fanMode: $('[name="fanMode_manual"]:checked').val(),
      acMode: $('[name="acMode_manual"]:checked').val(),
      targetTemp: Number($('#temperature_manual').html()) * 10,
      weekdays: weekdays.join(''),
      t1mode: $('#switchModeP1T1').val(),
      t1on: Number($('#port1Timer1Start').val().split(':').join('')),
      t1off: Number($('#port1Timer1End').val().split(':').join('')),
      t2mode: $('#switchModeP1T2').val(),
      t2on: Number($('#port1Timer2Start').val().split(':').join('')),
      t2off: Number($('#port1Timer2End').val().split(':').join('')),
      t3mode: $('#switchModeP1T3').val(),
      t3on: Number($('#port1Timer3Start').val().split(':').join('')),
      t3off: Number($('#port1Timer3End').val().split(':').join(''))
    };
    if (manualMode === '1') {
      submitParams = Object.assign(submitParams, {
        backAuto,
      });
    }
    if (manualMode === '0') {
      submitParams = Object.assign(submitParams, {
        allowIndependent: $('[name="allowIndep"]:checked').val(),
      });
    }

    if (urlmac) {
      submitParams = {
        act: 'upd',
        locationId: location_info.id,
        areaId: devid,
        mac: urlmac,
        dev_name: $('#dev_name').val(),
        areamode: manualMode,
        fanMode: $('[name="fanMode_manual"]:checked').val(),
        acMode: $('[name="acMode_manual"]:checked').val(),
        targetTemp: Number($('#temperature_manual').html()) * 10,
      }
      url = 'https://api.nevegy.com/index.php/api/manage?mtd=ModifyACDevice';
    }
    console.log(submitParams, url);
    // return;
    axios({
      method: 'post',
      url,
      // url: 'https://api.nevegy.com/index.php/api/manage?mtd=GetInfoByToken',
      data: submitParams
    })
      .then(function (response: any) {
        console.log(response);
        $('#dialog p').html('Successfully!');
        dialogObj.ok();
        dialogObj.open();
      })
      .catch(function (error: any) {
        console.log(error);
        dialogObj.no();
        $('#dialog p').html('Failed!!!');
        dialogObj.open();
      });
  });
}

function mode0(areaMode: any) {
  manmodeToggle(true);
  const {fanmode, acmode, targettemp} = areaMode;
  manModeVals({fanmode, acmode, targettemp});
}

function mode1(areaMode: any) {
  manmodeToggle(false);
  const {fanmode, acmode, targettemp} = areaMode;
  manModeVals({fanmode, acmode, targettemp});
}

function acdev(data: any) {
  console.log(data);

  $('#manualMode1').val(0);
  $('#manualMode2').val(1);
  $('#acMode_manual0').removeClass('none').next().removeClass('none');
  $('#areaName').addClass('none').prev().addClass('none');
  $('.hour-title, .hour-subtitle, .week-group, .time-title, .time-subtitle, .time').addClass('none');
  $('#backauto').addClass('none').prev().addClass('none');

  const {f_areamode, f_fanmode, f_acmode, f_targettemp, f_name} = data;

  $('#dev_name').removeClass('none').val(f_name).prev().removeClass('none');
  $('[name="manualMode"][value="' + f_areamode + '"]').attr('checked', true);

  if (f_areamode === 1) {
    mode0(areaMode);
  }
  if (f_areamode === 0) {
    mode1({fanmode: f_fanmode, acmode: f_acmode, targettemp: f_targettemp});
  }

  if (urlmac) {
    $('[name="manualMode"]').on('click', () => {
      if ($('[name="manualMode"]:checked').val() === '0') {
        mode1({fanmode: f_fanmode, acmode: f_acmode, targettemp: f_targettemp});
      } else {
        mode0(areaMode);
      }
    });
  }
}

function checktimer(dom: any) {
  if (dom.value === '0') {
    $(dom).siblings().removeClass('visible');
  } else {
    $(dom).siblings().addClass('visible');
  }
}
